package com.design.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.design.blog.dao.ArticleMapper;
import com.design.blog.model.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author hxg
 * @version 1.0
 * @date 2022/3/24 20:24
 */
@Component
public class ThreadService {

    @Async("taskExecutor")
    public void updArticleViews(ArticleMapper articleMapper, Article article) {
        Long updViews = article.getViews()+1;
        Article updArticle = new Article();
        updArticle.setViews(updViews);
        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Article::getId, article.getId());
        //加上悲观锁的验证 防止多线程下 更新出问题
        wrapper.eq(Article::getViews, article.getViews());
        articleMapper.update(updArticle,wrapper);
    }

    @Async("taskExecutor")
    public void updArticleComments(ArticleMapper articleMapper, String articleId) {
        Article article = articleMapper.selectById(articleId);
        long updComments = article.getCommentCount() + 1;
        Article updArticle = new Article();
        updArticle.setCommentCount(updComments);
        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Article::getId, articleId);
        wrapper.eq(Article::getCommentCount, article.getCommentCount());
        articleMapper.update(updArticle, wrapper);

    }
}
